var index;
var isEdit = false;
$(function(){
   initTab("");
   searchBtnInit();
   initDeptRole();
   doBtnInit();
});


function doBtnInit() {
  $("#addUserBtn").on("click",function () {
    isEdit =false;
    layui.use(['layer'],function () {
      var layer = layui.layer,$=layui.$;
      index = layer.open({
        type:1,//类型
        area: ['auto', 'auto'],//定义宽和高
        title:'编辑用户',//题目
        shadeClose:false,//点击遮罩层关闭
        zIndex: 1,
        content: $('#layerOpen')//打开的内容
      });
    });
  });

  $("#saveUserBtn").on("click",function(){
      var userId = $("#userIdInput").val();
      var password = $("#passwordInput").val();
      var userName = $("#userNameInput").val();
      var userDept = $("#userDeptSelect").val();
      var roleId =  $("#userRoleSelect").val();
      if("" == userId){
        toastrComponent.show("warning", "请输入用户名");
        return;
      }
      if(userId.length > 10){
        toastrComponent.show("warning", "用户名最多10个字符！");
        return;
      }
      if("" == password){
        toastrComponent.show("warning", "请输入密码");
        return;
      }
      if(password.length > 10){
        toastrComponent.show("warning", "密码最多10个字符！");
        return;
      }
      if(password.length < 6){
        toastrComponent.show("warning", "密码最最少6个字符！");
        return;
      }
      if("" == userName){
        toastrComponent.show("warning", "请输入用户姓名");
        return;
      }
      if(userName.length > 10){
        toastrComponent.show("warning", "用户姓名最多10个字符！");
        return;
      }
      if(-1 == userDept){
        toastrComponent.show("warning", "请选择部门！");
        return;
      }if(-2 == roleId){
        toastrComponent.show("warning", "请选择角色！");
        return;
      }
      var url = "saveUser.do";
      if(isEdit){
        url = "editUser.do";
      }
      var editUserId= $("#editUserId").val();
      $.ajax({
        type: "get",
        url: url,
        data: {
          "id": editUserId,
          "userId": userId,
          "password": password,
          "userName":userName,
          "roleId":roleId,
          "userDept":userDept
        },
        success: function (data) {
          if (data == "success") {
            tablerelaod("userTab");
            toastrComponent.show("success", "保存成功");
            var form = layui.form;
            form.val("userForm", {
              "userDeptSelect": "-1",
              "userRoleSelect": "-2"
            })
          }
          layer.close(index);
        }
      });

  });

  $("#userTableDiv").on("click",".editUser",function () {
    isEdit =true;
    layui.use(['layer'],function () {
      var layer = layui.layer,$=layui.$;
      index = layer.open({
        type:1,//类型
        area: ['auto', 'auto'],//定义宽和高
        title:'编辑用户',//题目
        shadeClose:false,//点击遮罩层关闭
        zIndex: 1,
        content: $('#layerOpen')//打开的内容
      });
    });

    var userId = $(this).attr("id");
    $("#editUserId").val(userId);

    $.ajax({
      type: "get",
      url: "getUserById.do",
      data: {
        "id": userId
      },
      success: function (data) {
        $("#userIdInput").val(data.userId);
        $("#passwordInput").val(data.password);
        $("#userNameInput").val(data.userName);
        var form = layui.form;
        form.val("userForm", {
          "userDeptSelect": data.userDept,
          "userRoleSelect": data.roleId
        })
      }
    });

  });
  $("#userTableDiv").on("click",".deleteUser",function () {
    var userId = $(this).attr("id");
    swal({
      title: "你确定要删除该附件？",
      type: "warning",
      allowOutsideClick: true,
      showConfirmButton: true,
      showCancelButton: true,
      confirmButtonClass: "layui-btn layui-btn-warm",
      cancelButtonClass: "layui-btn layui-btn-primary",
      confirmButtonText: "确认",
      cancelButtonText: "取消"
    }, function (o) {
      if (o) {
        $.ajax({
          type: "get",
          url: "deleteUser.do",
          data: {
            "id": userId
          },
          success: function (data) {
            if (data == "success") {
              toastrComponent.show("success", "删除成功!");
              tablerelaod("userTab");
            }
          }
        });
      }
    });
  });

  $("#userTableDiv").on("click",".transferData",function () {
    layui.use(['layer'],function () {
      var layer = layui.layer,$=layui.$;
      index = layer.open({
        type:1,//类型
        area: ['auto', 'auto'],//定义宽和高
        title:'数据转移',//题目
        shadeClose:false,//点击遮罩层关闭
        zIndex: 1,
        content: $('#layerOpen1')//打开的内容
      });
    });
    var userId = $(this).attr("id");
    $("#transferUserId").val(userId);
    $.ajax({
      type: "get",
      url: "getAllUser.do",
      success: function (data) {
        var html = '<option value="">选择或搜索</option>';
        //var html = '';
        $.each(data, function (i, item) {
          html += '<option value="' + item.id + '">' + item.userName + '</option>';
        });
        $("#userSelect").html(html);
        var form = layui.form;
        form.render('select');
      }
      });
  });

  $("#cancelBtn").on("click", function () {
    layer.close(index);
  });

  $("#transferBtn").on("click",function(){
    swal({
      title: "你确定要将该用户的数据转移？",
      type: "warning",
      allowOutsideClick: true,
      showConfirmButton: true,
      showCancelButton: true,
      confirmButtonClass: "layui-btn layui-btn-warm",
      cancelButtonClass: "layui-btn layui-btn-primary",
      confirmButtonText: "确认",
      cancelButtonText: "取消"
    }, function (o) {
      if (o) {
        var srcUserId = $("#transferUserId").val();
        var targetUserId = $("#userSelect").val();
        $.ajax({
          type: "get",
          url: "transferData.do",
          data:{
            "srcUserId" : srcUserId,
            "targetUserId" : targetUserId
          },
          success: function (data) {
            toastrComponent.show("success", "数据转移成功!");
          }
        });
        layer.close(index);
      }
    });
  });

}

//初始化部门，角色
function initDeptRole() {
  $.ajax({
    type: "get",
    url: "getAllRole.do",
    success: function (data) {
      var html =  '<option value="-2">请选择</option>';
      $.each(data, function (i, item) {
        html += '<option value="'+item.roleId+'">'+item.roleName+'</option>';
      });
      $("#userRoleSelect").html(html);
      $.ajax({
        type: "get",
        url: "getAllDept.do",
        success: function (data1) {
          var html =  '<option value="-1">请选择</option>';
          $.each(data1, function (i, item) {
            html += '<option value="'+item.deptId+'">'+item.deptName+'</option>';
          });
          $("#userDeptSelect").html(html);
          layui.use(['form'], function () {
            var form = layui.form;
            form.render('select');
          });
        }
      });
    }
  });

}


//搜索按钮事件
function searchBtnInit() {
	$("#searchBtn").on("click",function () {
		var serachStr = $("#searchStr").val();
    initTab(serachStr);
  });
}

//初始化表格
function initTab(search) {
  layui.use(['table'], function() {
    var table = layui.table;
    table.render({
      elem: '#userTab'
      , url: 'getUserList.do?search=' + search
      , height: '480',
      page: {
        layout: ['count', 'prev', 'page', 'next', 'skip']
        , groups: 1 //只显示 1 个连续页码
        , first: false //不显示首页
        , last: false //不显示尾页
        , limit: 10
        , limits: [10]
      }
      , cols: [[
        {field: 'userId', align: 'center', width: '15%', title: '用户名'}
        ,{field: 'password', align: 'center', width: '15%', title: '密码'}
        , {field: 'userName', align: 'center', width: '15%', title: '用户姓名'}
        , {field: 'userDeptName', align: 'center', width: '20%', title: '部门'}
        , {field: 'roleName', align: 'center', width: '15%', title: '角色'}
        , {
          field: 'id', align: 'center', width: '20.3%', title: '操作',
          templet: function (data) {
            var html = '';
            html += '<a class="layui-btn layui-btn-xs editUser" lay-event="edit" id='+data.id+'>编辑</a>';
            html += '<a class="layui-btn layui-btn-xs deleteUser" lay-event="edit" id='+data.id+'>删除</a>';
            html += '<a class="layui-btn layui-btn-xs transferData" lay-event="edit" id='+data.id+'>转移数据</a>';
            return html;
          }
        }
      ]]
    });
  })
}


function tablerelaod(tableId) {
  var table = layui.table;
  table.reload(tableId);
}